package org.linphone.activity;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.leehuubsd.yiyanzb.R;
import com.umeng.analytics.MobclickAgent;

import org.linphone.Bean.CustomerBean;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class QueryActivity extends Activity implements OnClickListener {
	private ImageView backbtn;
	private TextView iPhone, money, time, ytime;
	private CustomerBean bean;
	private String OEMID,http;
	private RelativeLayout query_rl;

	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		OEMID = getResources().getString(R.string.oem);
		http = getResources().getString(R.string.http);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_query);
		init();
	}

	private SharedPreferences sharedPreferences = null;
	private String nameE = null;
	private String numM = null;
	private String Phone = null;
	private TextView phoneYE = null;
	private TextView phoneYX;
	private Map<String, Object> map;

	private void init() {
		query_rl = (RelativeLayout) findViewById(R.id.query_rl);
		iPhone = (TextView) findViewById(R.id.iphone_tv);
		money = (TextView) findViewById(R.id.money_tv);
		time = (TextView) findViewById(R.id.time_tv);
		backbtn = (ImageView) findViewById(R.id.back_btn);
		backbtn.setOnClickListener(this);
		sharedPreferences = getSharedPreferences("bosideng",
				Context.MODE_WORLD_READABLE);
		Phone = sharedPreferences.getString("Phone", null);
		numM = sharedPreferences.getString("CardPassWord", null);
		iPhone.setText(Phone);
		if (networkStatusOK()) {
			postDataToNe("/YXBp/dm9zb2Vt/R2V0VXNlckluZm8PQ", numM, Phone);
		} else {
			Toast.makeText(this, "无网络连接...", Toast.LENGTH_SHORT).show();
		}
	}

	private boolean networkStatusOK() {
		try {
			ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivity != null) {
				NetworkInfo info = connectivity.getActiveNetworkInfo();
				if (info != null && info.isConnected()) {
					if (info.getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		} catch (Exception e) {
			return false;
		}
		return false;
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.back_btn:
			finish();
			break;

		default:
			break;
		}

	}


	public CustomerBean parserToObject(String json) {
		try {
			JSONTokener jsonTokener = new JSONTokener(json);
			JSONObject object = (JSONObject) jsonTokener.nextValue();
			int i = object.getInt("retCode");
			if (i == 0) {
				//{"retCode":0,"accountInfo":{"balance":86.200000000000017,"enddate":1497583103797,"isMonth":false,"monthlyValidityDays":0}}

				bean = new CustomerBean();
				JSONObject object2 = (JSONObject) object.get("accountInfo");
				bean.setBalance(object2.getDouble("balance"));
				bean.setEnddate(object2.getLong("enddate"));
				bean.setMonth(object2.getBoolean("isMonth"));
				bean.setMonthlyValidityDays(object2
						.getInt("monthlyValidityDays"));
			} else {
				Toast.makeText(
						getApplicationContext(),
						object.getString("exception") + "("
								+ object.getInt("retCode") + ")",
						Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return bean;

	}


	/**
	 * post请求
	 * 
	 * @author li Feb 4, 2015
	 */
	private void postDataToNe(String path, final String CardPassword,
			final String Phone) {
		RequestQueue queue = Volley.newRequestQueue(this);
		StringRequest request = new StringRequest(Method.POST, http + path,
				new Listener<String>() {
					@Override
					public void onResponse(String response) {
						Log.i("LOL", response);
						parserToObject(response);
						try {
							iPhone.setText(Phone);
							DecimalFormat df = new DecimalFormat("######0.00");
							money.setText(df.format(bean.getBalance()) + "元");
//							int time1 = bean.getMonthlyValidityDays();
//							if (bean.isMonth() && time1 > 0) {
//								time.setText(time1 + "天");
//								query_rl.setVisibility(View.VISIBLE);
//							}
							long enddate = Math.abs(bean.getEnddate());
//							SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日"); 
//								String sd = sdf.format(new Date(enddate*1000));
//								time.setText(sd);
								
							String date = new java.text.SimpleDateFormat("yyyy年MM月dd日").format(new java.util.Date(enddate));
							time.setText(date);
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				}, new ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError arg0) {
						Log.i("LOG", "!!!!onErrorResponse：" + arg0.toString());
						Toast.makeText(getApplicationContext(), "获取数据失败，请稍后再试",
								0).show();
						finish();
					}
				}) {
			protected Map<String, String> getParams() throws AuthFailureError {
				String p = encryptBASE64(Phone);
				Map<String, String> map = new HashMap<String, String>();
				map.put("dXNlck5hbWUPQ", p);
				map.put("password", CardPassword);
				map.put("proxyId", OEMID);
				return map;
			}
		};
		queue.add(request);
	}

	/**
	 * BASE64 加密
	 * 
	 * @param str
	 * @return
	 */
	public String encryptBASE64(String str) {
		if (str == null || str.length() == 0) {
			return null;
		}
		try {
			byte[] encode = str.getBytes("UTF-8");
			// base64 加密

			String s = new String(Base64.encode(encode, 0, encode.length,
					Base64.DEFAULT), "UTF-8");
			String s1 = s.replaceAll("=", "PQ");
			Log.i("LOL", s1);
			return s1;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return null;
	}

}
